﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Xna.Framework;

namespace Daybreak.Core.SceneGraph
{
    /// <summary>
    /// Switch is a Group node that allows switching between children. 
    /// </summary>
    /// <remarks>
    /// Typical uses would be for objects which might need to be rendered differently at different times
    /// </remarks>
    public class Switch : Group
    {
        public delegate void Method(Switch node, float deltaTime);

        private int _nodeIndex;
        public event Method Expression;

        public Switch() { }

        public override void Update(NodeVisitor updater, float deltaTime)
        {
            if (Expression != null)
                Expression(this, deltaTime);

            base.Update(updater, deltaTime);
        }

        public override void Accept(NodeVisitor visitor)
        {
            visitor.VisitSwitch(this);

            Node node = ActiveNode;

            if (node == null)
                return;

            // forward visitor to the active node
            node.Accept(visitor);
        }

        public override void ComputeBound(ref BoundingBox result)
        {
            Node node = ActiveNode;

            if (node == null)
                return;

            node.ComputeBound(ref result);

        }

        public override void LocalToWorld(ref Matrix result)
        {
            Node node = ActiveNode;

            if (node == null)
                base.LocalToWorld(ref result);
            else
                node.LocalToWorld(ref result);
        }

        public override void WorldToLocal(ref Matrix result)
        {
            Node node = ActiveNode;

            if (node == null)
                base.WorldToLocal(ref result);
            else
                node.WorldToLocal(ref result);
        }

        public int ActiveNodeIndex
        {
            get { return _nodeIndex; }
            set
            {
                if (value < 0 || value >= _children.Count)
                    return;

                _nodeIndex = value;
            }
        }

        public Node ActiveNode
        {
            get
            {
                if (_nodeIndex < 0 || _nodeIndex >= _children.Count)
                    return null;

                Node node = _children[_nodeIndex];

                return node;

            }
        }

        public List<Node> SwitchNodes
        {
            get { return _children; }
        }
    }
}
